﻿using System;

namespace Tentacle
{
    using System.Threading.Tasks;

    using Tentacle.Core;
    using Tentacle.Processor;
    using Tentacle.Downloader;

    class Program
    {
        static TentacleCore core;

        static void Main(string[] args)
        {
            var processor = new Hjav5268Processor();
            processor.Create(@"E:\R18\database.sqlite");
            core = new TentacleCore(new IPageProcessor[]{processor},processor,5000);
            core.CacheFolder = @"E:\R18";
            core.IsCacheRawHtml = false;


            Console.ForegroundColor = ConsoleColor.DarkGreen;

            core.DownloadCompleted += Core_DownloadCompleted;//+= (site) => Console.WriteLine($"[finish]  {DateTime.Now} {site}");
            core.DownloadFailed += Core_DownloadFailed;//+= (error) => Console.WriteLine($"[error]  {DateTime.Now}  {error}");

            Task.Factory.StartNew(MainLoop);

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
            
            while (true) {
                var msg = Console.ReadLine();
                switch (msg.ToLower()) {
                    case "dump":
                        core.SaveProgress("E:\\R18");
                        break;
                    case "start":
                        core.Start("http://porn68jav.com/category/censored/");
                        break;
                    case "load":
                        core.LoadProgress(@"E:\R18");
                        break;
                    case "count":
                        Console.WriteLine($"已完成:{core.FinishedCount},未完成:{core.UnFinishedCount}");
                        break;
                }
            }
        }

        private static void Core_DownloadFailed(string obj)
        {
            Console.WriteLine($"[error]  {DateTime.Now} {obj}");
        }

        private static void Core_DownloadCompleted(string obj)
        {
            Console.WriteLine($"[finish]  {DateTime.Now} {obj}");
        }

        private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            core.SaveProgress(@"E:\R18");            
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            core.SaveProgress(@"E:\R18");
        }

        async static void MainLoop()
        {
            int i = 0;
            while (true) {
                await Task.Delay(1000);
                i++;
                if(i == 60) {
                    Console.Clear();
                    Console.WriteLine($"已完成:{core.FinishedCount},未完成:{core.UnFinishedCount}");
                }

            }
        }
    }
}
